package com.program.beautymakeup.exception;


import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.hutool.core.exceptions.ExceptionUtil;
import com.program.beautymakeup.domain.vo.ResultInfo;
import com.program.beautymakeup.utils.ResultInfoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 * @create 2022/11/11-9:17
 **/
@ControllerAdvice
@Slf4j
public class ExceptionCatch {

    @ExceptionHandler(NotLoginException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ResultInfo<Void> NotLoginException(NotLoginException notLoginException){
        // 记录日志
        log.error("catch NotLoginException error:{}",notLoginException.toString());
        return ResultInfoUtil.buildError(401,"未登录");
    }
    @ExceptionHandler(NotRoleException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ResultInfo<Object> NotRoleException(NotRoleException notRoleException){
        // 记录日志
        log.error("catch NotRoleException,error:{}",notRoleException.toString());
        return ResultInfoUtil.buildError(401,"无权限");
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultInfo<Object> Exception(Exception exception){
        // 记录日志
        log.error("catch Exception error:{}",ExceptionUtil.stacktraceToString(exception));
        return ResultInfoUtil.buildError(exception.getMessage());
    }


    @ExceptionHandler(BindException.class)
    @ResponseBody
    public ResultInfo<Object> bindException(BindException bindException){
        // 记录日志
        List<String> list = bindException.getFieldErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList());
        return ResultInfoUtil.buildError(list.toString());
    }


}
